package rpcserver

import (
	"fmt"
	corev1 "gluenet/internal/agent/api/core/v1"
	rpcv1 "gluenet/internal/agent/api/rpc/v1"
	"gluenet/internal/agent/depend"
	"gluenet/internal/agent/driver/rpcdriver"
	"gluenet/internal/agent/driver/rpcserver"
	"gluenet/internal/agent/server"
)

var (
	inits = make(map[string]func(c rpcserver.IRoutes))
)

func registerRouter(router string, init func(c rpcserver.IRoutes)) {
	inits[router] = init
}

func InitServer(cfg *corev1.Agent) (server.Server, error) {

	services := cfg.RpcServices
	if len(services) == 0 {
		return nil, nil
	}

	router := rpcserver.Default()
	r := router.Group(rpcv1.RpcAgentApiPerfix)

	for _, service := range services {

		if init, ok := inits[service]; ok {
			init(r)
		} else {
			return nil, fmt.Errorf("invalid service: %s", service)
		}

	}

	svr := &rpcserver.RpcServer{
		Guid:       cfg.Guid,
		RpcHandler: router.Handlers(),
		RpcConfig:  depend.Produce[*rpcdriver.RpcConfig]().NatsUrl,
	}

	return svr, nil
}
